<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\MessageBag;
use App\Admin\Extensions\OrderDeliver;
use App\Admin\Models\ShareBonus;
use Field\Interaction\FieldTriggerTrait;
use Field\Interaction\FieldSubscriberTrait;
use DB;

class shareBonusController extends Controller
{
	use HasResourceActions, FieldTriggerTrait, FieldSubscriberTrait;
	
    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('店铺分红')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('添加分红')
            ->description('')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('添加分红')
            ->description('新增')
            ->body($this->form());
    }
    
//  public function update(Request $request, $id)
//  {
//
//  }
    
//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {	
//  	
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ShareBonus);
        $grid->sbId('ID');
        $grid->sbMonth('分红月份');
        $grid->totalProfit('当月利润');
		$grid->sbShareMoney('分红总金额');
		$grid->sbTransferMoney('利润保留');
		$grid->column('详细')->expand(function ($model) {
			
			$dataArray = array();
			foreach($this->logList as $logInfo){
				$logInfo = json_decode(json_encode($logInfo), true);
				$tempArray = array();
				array_push($tempArray, $logInfo['slId']);
				array_push($tempArray, $logInfo['sbMonth']);
				array_push($tempArray, $logInfo['name']);
				array_push($tempArray, $logInfo['alMoney']);
				array_push($tempArray, $logInfo['auStock']);
				array_push($dataArray, $tempArray);
			}
            

            return new Table(['ID', '分红月', '分红股东', '分红金额', '持股百分比%'], $dataArray);
        });
        $grid->createUser('操作人');
        $grid->createTime('操作时间');
        
//      // 不存的字段列
//		$grid->column('full_name')->display(function () {
//		    return $this->first_name.' '.$this->last_name;
//		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
		});
		
		// 获取当前行数据
		$grid->actions(function ($actions) {

		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
		});
		
		// 禁用创建按钮
//		$grid->disableCreateButton();

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		// 禁用导出数据按钮
//		$grid->disableExport();
		
		// 禁用行操作列
		$grid->disableActions();
		
		// 禁用分页条
		//$grid->disablePagination();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Order = new Order();
        $show = new Show($Order->findOrFail($id));

        $show->order_id('ID');
        $show->shop_name('商家名称');
        $show->user_name('用户姓名');
		$show->goods_name('商品名称');
		$show->goods_skus('商品规格')->badge();;
        $show->pay_money('支付金额');
        $show->order_status('订单状态')->using(['-1' => '退单', '0' => '未发货', '1' => '已发货', '2' => '已收货', '3' => '已评价']);
        $show->pay_time('下单时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::Form(ShareBonus::class, function (Form $form) {

			$sId = Admin::user()->sId;
			$sInfo = DB::table('store')->where('sId', $sId)->first();
			
			
			$form->select('sbMonth', '分红月份')->options($this->getUsableMonthSelect())->rules("required", ['required' => '请选择分红月份']);//default定义默认值为数据表中sort字段的最大值+1
			$form->text('totalProfit', '总利润')->default(0)->readOnly();
			$form->text('sbTransferMoney', '保留金额')->default(0);
            
            // 弄一个触发事件的Script对象。
        	$trigger_script = $this->createTriggerScript($form);
        	// 添加事件响应事件
        	$subscriber_script = $this->createSubscriberScript($form, function($builder) use($sId) {

	            $builder->subscribe('sbMonth', 'select', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		var sId = {$sId};
							var month = data.id;

							var url = "../../main/getMonthProfit?sId={$sId}&month="+month;
						
						    $.get(url, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}
						    	
						    	$("#totalProfit").val(data.data);
						    });
	                	}
EOT;
					return $script;
	            });
	            
	            
       		});

       		/* 将 trigger_script 和 subscriber_script 注入 form 中 */
        	$form->scriptinjecter('name_no_care', $trigger_script, $subscriber_script);
            
            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();
				
			    // 去掉`删除`按钮
//			    $tools->disableDelete();
			
			    // 去掉`查看`按钮
			    $tools->disableView();
			
			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});
			
			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//			
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();
			
			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();
			
			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();
			
			    // 去掉`继续创建`checkbox
			    $footer->disableCreatingCheck();
			
			});
			
			$form->saving(function (Form $form) {
			    $totalProfit = $form->totalProfit;
				$sbTransferMoney = $form->sbTransferMoney;
				if ($sbTransferMoney > $totalProfit){
					$error = new MessageBag([
						'title'   => '提交失败',
				        'message' => '保留金额不能大于总利润'
				    ]);
				
				    return back()->with(compact('error'))->withInput();
				}
			});
        });
    }
    
    public function getUsableMonthSelect(){
    	
    	$sId = Admin::user()->sId;
    	$list = DB::select("SELECT *
FROM sys_month AS sm 
WHERE sm.`month` NOT IN
(
SELECT sb.sbMonth
FROM share_bonus AS sb
WHERE sb.sId = ?
)
AND sm.`month` < date_format(NOW(), '%Y-%m')
LIMIT 0, 12", [$sId]);
		
		$returnArray = array();
		foreach($list as $monthInfo){
			$returnArray[$monthInfo->month] = $monthInfo->month;
		}
    	
    	return $returnArray;
    }
}
